﻿namespace Hidistro.UI.Web.AppShop
{
    using Hidistro.ControlPanel.Store;
    using Hidistro.Core;
    using Hidistro.Core.Entities;
    using Hidistro.Core.Enums;
    using Hidistro.Entities;
    using Hidistro.Entities.Commodities;
    using Hidistro.Entities.Members;
    using Hidistro.Entities.Orders;
    using Hidistro.Entities.VShop;
    using Hidistro.Membership.Context;
    using Hidistro.Membership.Core;
    using Hidistro.Membership.Core.Enums;
    using Hidistro.Messages;
    using Hidistro.SaleSystem.Catalog;
    using Hidistro.SaleSystem.Member;
    using System;
    using System.Collections.Generic;
    using System.Data;
    using System.Text;
    using System.Web;
    using System.Web.Security;

    public class AppShopHandler : IHttpHandler
    {
        private void GetCategories(HttpContext context)
        {
            string str = context.Request["pid"];
            if (string.IsNullOrEmpty(str))
            {
                context.Response.Write(this.GetErrorJosn(0x65, "缺少必填参数"));
            }
            else
            {
                int result = 0;
                if (!int.TryParse(str, out result))
                {
                    context.Response.Write(this.GetErrorJosn(0x66, "数字类型转换错误"));
                }
                else
                {
                    IList<CategoryInfo> mainCategories = null;
                    if (result == 0)
                    {
                        mainCategories = CategoryBrowser.GetMainCategories();
                    }
                    else
                    {
                        mainCategories = CategoryBrowser.GetSubCategories(result);
                    }
                    if ((mainCategories == null) || (mainCategories.Count == 0))
                    {
                        context.Response.Write(this.GetErrorJosn(0x67, "没获取到相应的分类"));
                    }
                    else
                    {
                        StringBuilder builder = new StringBuilder();
                        builder.Append("{\"result\":[");
                        foreach (CategoryInfo info in mainCategories)
                        {
                            builder.Append("{");
                            builder.AppendFormat("\"cid\":{0},", info.CategoryId);
                            builder.AppendFormat("\"name\":\"{0}\",", info.Name);
                            builder.AppendFormat("\"icon\":\"{0}\",", info.Icon);
                            builder.AppendFormat("\"hasChildren\":\"{0}\",", info.HasChildren.ToString().ToLower());
                            builder.AppendFormat("\"description\":\"{0}\"", this.GetSubCategoryNames(info.CategoryId));
                            builder.Append("},");
                        }
                        builder.Remove(builder.Length - 1, 1);
                        builder.Append("]}");
                        context.Response.Write(builder.ToString());
                    }
                }
            }
        }

        private void GetDefaultData(HttpContext context)
        {
            StringBuilder builder = new StringBuilder();
            builder.Append("{\"result\":{\"advs\":[");
            IList<BannerInfo> allBanners = VShopHelper.GetAllBanners(ClientType.App);
            if ((allBanners != null) && (allBanners.Count > 0))
            {
                foreach (BannerInfo info in allBanners)
                {
                    builder.Append("{");
                    builder.AppendFormat("\"pic\":\"{0}\",", Globals.FullPath(info.ImageUrl));
                    builder.AppendFormat("\"description\":\"{0}\",", info.ShortDesc);
                    builder.AppendFormat("\"url\":\"{0}\"", info.LoctionUrl);
                    builder.Append("},");
                }
                builder.Remove(builder.Length - 1, 1);
            }
            builder.Append("],");
            builder.Append("\"tagProducts\":[");
            DataTable homeProducts = VShopHelper.GetHomeProducts(ClientType.App);
            if ((homeProducts != null) && (homeProducts.Rows.Count > 0))
            {
                foreach (DataRow row in homeProducts.Rows)
                {
                    builder.Append("{");
                    builder.AppendFormat("\"pid\":{0},", row["ProductId"]);
                    builder.AppendFormat("\"name\":\"{0}\",", row["ProductName"]);
                    builder.AppendFormat("\"pic\":\"{0}\",", (row["ThumbnailUrl180"] != DBNull.Value) ? Globals.FullPath((string) row["ThumbnailUrl180"]) : "");
                    builder.AppendFormat("\"price\":\"{0}\",", ((decimal) row["SalePrice"]).ToString("F0"));
                    builder.AppendFormat("\"saleCounts\":\"{0}\",", ((int) row["ShowSaleCounts"]).ToString());
                    builder.AppendFormat("\"url\":\"{0}\"", Globals.FullPath(string.Format("/AppShop/ProductDetails.aspx?productId={0}", row["ProductId"])));
                    builder.Append("},");
                }
                builder.Remove(builder.Length - 1, 1);
            }
            builder.Append("]}}");
            context.Response.Write(builder.ToString());
        }

        private string GetErrorJosn(int errorCode, string errorMsg)
        {
            return ("{\"error_response\":{\"errorCode\":" + string.Format("{0}, \"errorMsg\":\"{1}\"", errorCode, errorMsg) + "}}");
        }

        private void GetMember(HttpContext context)
        {
            string str = context.Request["sessionid"];
            if (string.IsNullOrEmpty(str))
            {
                context.Response.Write(this.GetErrorJosn(0x65, "缺少必填参数"));
            }
            else
            {
                Member userBySessionId = Users.GetUserBySessionId(str) as Member;
                if (userBySessionId == null)
                {
                    context.Response.Write(this.GetErrorJosn(0x6b, "sessionid过期或不存在，请重新登录"));
                }
                else
                {
                    MemberGradeInfo memberGrade = MemberProcessor.GetMemberGrade(userBySessionId.GradeId);
                    string str2 = (memberGrade == null) ? "" : memberGrade.Name;
                    OrderQuery query = new OrderQuery {
                        Status = OrderStatus.WaitBuyerPay
                    };
                    int userOrderCount = MemberProcessor.GetUserOrderCount(userBySessionId.UserId, query);
                    query.Status = OrderStatus.SellerAlreadySent;
                    int num2 = MemberProcessor.GetUserOrderCount(userBySessionId.UserId, query);
                    StringBuilder builder = new StringBuilder();
                    builder.Append("{\"result\":{");
                    builder.AppendFormat("\"uid\":{0},", userBySessionId.UserId);
                    builder.AppendFormat("\"sessionid\":\"{0}\",", userBySessionId.SessionId);
                    builder.AppendFormat("\"gradeName\":\"{0}\",", str2);
                    builder.AppendFormat("\"realName\":\"{0}\",", string.IsNullOrEmpty(userBySessionId.RealName) ? userBySessionId.Username : userBySessionId.RealName);
                    builder.AppendFormat("\"waitPayCount\":\"{0}\",", userOrderCount);
                    builder.AppendFormat("\"waitFinishCount\":\"{0}\",", num2);
                    builder.AppendFormat("\"orderNumber\":\"{0}\",", userBySessionId.OrderNumber);
                    builder.AppendFormat("\"expenditure\":\"{0}\",", userBySessionId.Expenditure.ToString("F0"));
                    builder.AppendFormat("\"points\":\"{0}\"", userBySessionId.Points);
                    builder.Append("}}");
                    context.Response.Write(builder.ToString());
                }
            }
        }

        private void GetProducts(HttpContext context)
        {
            int num = 1;
            int num2 = 10;
            if (!string.IsNullOrEmpty(context.Request["pageIndex"]))
            {
                int.TryParse(context.Request["pageIndex"], out num);
            }
            if (!string.IsNullOrEmpty(context.Request["pageSize"]))
            {
                int.TryParse(context.Request["pageSize"], out num2);
            }
            ProductBrowseQuery query = new ProductBrowseQuery {
                PageIndex = num,
                PageSize = num2
            };
            if (!string.IsNullOrEmpty(context.Request["cId"]))
            {
                int result = 0;
                int.TryParse(context.Request["cId"], out result);
                if (result != 0)
                {
                    query.CategoryId = new int?(result);
                }
            }
            query.Keywords = context.Request["keyword"];
            query.SortBy = "DisplaySequence";
            query.SortOrder = SortAction.Desc;
            if (!string.IsNullOrEmpty(context.Request["sortBy"]))
            {
                query.SortBy = context.Request["sortBy"];
            }
            if (!string.IsNullOrEmpty(context.Request["sortOrder"]) && (context.Request["sortOrder"] == "asc"))
            {
                query.SortOrder = SortAction.Asc;
            }
            DbQueryResult browseProductList = ProductBrowser.GetBrowseProductList(query);
            DataTable data = (DataTable) browseProductList.Data;
            if ((data == null) || (data.Rows.Count == 0))
            {
                context.Response.Write(this.GetErrorJosn(0x67, "没获取到相应的商品"));
            }
            else
            {
                StringBuilder builder = new StringBuilder();
                builder.Append("{\"result\":{");
                builder.AppendFormat("\"totals\":{0},", browseProductList.TotalRecords);
                builder.Append("\"products\":[");
                foreach (DataRow row in data.Rows)
                {
                    builder.Append("{");
                    builder.AppendFormat("\"pid\":{0},", row["ProductId"]);
                    builder.AppendFormat("\"name\":\"{0}\",", row["ProductName"]);
                    builder.AppendFormat("\"pic\":\"{0}\",", (row["ThumbnailUrl60"] == DBNull.Value) ? "" : Globals.FullPath((string) row["ThumbnailUrl60"]));
                    builder.AppendFormat("\"price\":\"{0}\",", ((decimal) row["SalePrice"]).ToString("F0"));
                    builder.AppendFormat("\"saleCounts\":\"{0}\",", ((int) row["SaleCounts"]).ToString());
                    builder.AppendFormat("\"url\":\"{0}\"", Globals.FullPath(string.Format("/AppShop/ProductDetails.aspx?productId={0}", row["ProductId"])));
                    builder.Append("},");
                }
                builder.Remove(builder.Length - 1, 1);
                builder.Append("]}}");
                context.Response.Write(builder.ToString());
            }
        }

        private string GetSubCategoryNames(int parentCategoryId)
        {
            IList<CategoryInfo> subCategories = CategoryBrowser.GetSubCategories(parentCategoryId);
            StringBuilder builder = new StringBuilder();
            if ((subCategories != null) && (subCategories.Count > 0))
            {
                foreach (CategoryInfo info in subCategories)
                {
                    builder.Append(info.Name).Append(" ");
                }
                builder.Remove(builder.Length - 1, 1);
            }
            return builder.ToString();
        }

        private void ProcessAppInit(HttpContext context)
        {
            string str = context.Request["VID"];
            string str2 = context.Request["device"];
            string str3 = context.Request["version"];
            string str4 = context.Request["isFirst"];
            if ((string.IsNullOrEmpty(str) || string.IsNullOrEmpty(str2)) || (string.IsNullOrEmpty(str3) || string.IsNullOrEmpty(str4)))
            {
                context.Response.Write(this.GetErrorJosn(0x65, "缺少必填参数"));
            }
            else
            {
                decimal num;
                if (!decimal.TryParse(str3, out num))
                {
                    context.Response.Write(this.GetErrorJosn(0x66, "数字类型转换错误"));
                }
                else
                {
                    if (str4.ToLower() == "true")
                    {
                        AppInstallRecordInfo appInstallRecord = new AppInstallRecordInfo {
                            VID = str,
                            Device = str2
                        };
                        APPHelper.AddAppInstallRecord(appInstallRecord);
                    }
                    AppVersionRecordInfo latestAppVersionRecord = APPHelper.GetLatestAppVersionRecord(str2);
                    if (latestAppVersionRecord == null)
                    {
                        latestAppVersionRecord = new AppVersionRecordInfo {
                            Version = num
                        };
                    }
                    StringBuilder builder = new StringBuilder();
                    builder.Append("{\"result\":{");
                    builder.AppendFormat("\"version\":\"{0}\",", latestAppVersionRecord.Version);
                    bool flag = latestAppVersionRecord.Version > num;
                    builder.AppendFormat("\"existNew\":\"{0}\",", flag.ToString().ToLower());
                    builder.AppendFormat("\"forcible\":\"{0}\",", APPHelper.IsForcibleUpgrade(str2, num).ToString().ToLower());
                    builder.AppendFormat("\"description\":\"{0}\",", latestAppVersionRecord.Description);
                    builder.AppendFormat("\"upgradeUrl\":\"{0}\"", latestAppVersionRecord.UpgradeUrl);
                    builder.Append("}}");
                    context.Response.Write(builder.ToString());
                }
            }
        }

        private void ProcessLogin(HttpContext context)
        {
            string str = context.Request["userName"];
            string str2 = context.Request["password"];
            if (string.IsNullOrEmpty(str) || string.IsNullOrEmpty(str2))
            {
                context.Response.Write(this.GetErrorJosn(0x65, "缺少必填参数"));
            }
            else
            {
                Member member = Users.GetUser(0, str, false, true) as Member;
                if (member == null)
                {
                    context.Response.Write(this.GetErrorJosn(0xcd, "用户名无效"));
                }
                else
                {
                    member.Password = str2;
                    if (MemberProcessor.ValidLogin(member) != LoginUserStatus.Success)
                    {
                        context.Response.Write(this.GetErrorJosn(0xce, "密码有误"));
                    }
                    else
                    {
                        StringBuilder builder = new StringBuilder();
                        builder.Append("{\"result\":{");
                        builder.AppendFormat("\"uid\":{0},", member.UserId);
                        builder.AppendFormat("\"sessionid\":\"{0}\"", UserHelper.UpdateSessionId(member.UserId));
                        builder.Append("}}");
                        context.Response.Write(builder.ToString());
                    }
                }
            }
        }

        private void ProcessRegiester(HttpContext context)
        {
            string str = context.Request["userName"];
            string str2 = context.Request["password"];
            string str3 = context.Request["email"];
            if ((string.IsNullOrEmpty(str) || string.IsNullOrEmpty(str2)) || string.IsNullOrEmpty(str3))
            {
                context.Response.Write(this.GetErrorJosn(0x65, "缺少必填参数"));
            }
            else
            {
                Member member = new Member(UserRole.Member) {
                    GradeId = MemberProcessor.GetDefaultMemberGrade(),
                    SessionId = Globals.GetGenerateId(),
                    Username = str,
                    Email = str3,
                    Password = str2,
                    PasswordFormat = MembershipPasswordFormat.Hashed,
                    TradePasswordFormat = MembershipPasswordFormat.Hashed,
                    TradePassword = str2,
                    IsApproved = true,
                    RealName = string.Empty,
                    Address = string.Empty
                };
                switch (MemberProcessor.CreateMember(member))
                {
                    case CreateUserStatus.DuplicateUsername:
                    case CreateUserStatus.DisallowedUsername:
                        context.Response.Write(this.GetErrorJosn(0xc9, "用户名重复"));
                        return;

                    case CreateUserStatus.DuplicateEmailAddress:
                        context.Response.Write(this.GetErrorJosn(0xca, "邮件名重复"));
                        return;

                    case CreateUserStatus.Created:
                    {
                        Messenger.UserRegister(member, str2);
                        member.OnRegister(new UserEventArgs(member.Username, str2, null));
                        StringBuilder builder = new StringBuilder();
                        builder.Append("{\"result\":{");
                        builder.AppendFormat("\"uid\":{0},", member.UserId);
                        builder.AppendFormat("\"sessionid\":\"{0}\"", member.SessionId);
                        builder.Append("}}");
                        context.Response.Write(builder.ToString());
                        return;
                    }
                }
                context.Response.Write(this.GetErrorJosn(0x79, "注册用户失败"));
            }
        }

        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "application/json";
            switch (context.Request["action"])
            {
                case "appInit":
                    this.ProcessAppInit(context);
                    return;

                case "getDefaultData":
                    this.GetDefaultData(context);
                    return;

                case "getCategories":
                    this.GetCategories(context);
                    return;

                case "getProducts":
                    this.GetProducts(context);
                    return;

                case "regiester":
                    this.ProcessRegiester(context);
                    return;

                case "login":
                    this.ProcessLogin(context);
                    return;

                case "getMember":
                    this.GetMember(context);
                    return;
            }
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}

